/**
 *
 */
package com.bims.jreport.exception;

import cn.hutool.core.util.StrUtil;
import com.bims.jreport.controller.RestResult;
import com.bims.jreport.utils.I18nMessagesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 一般性逻辑错误，逻辑判断，逻辑异常处理
 *
 * @author wangrenjie
 */

@Slf4j
@Component
public class LogicRunTimeException extends RuntimeException implements ApplicationContextAware {

    private static final long serialVersionUID = -1730436714943902082L;

    private static I18nMessagesUtil messageUtil;

    private String errorCode;
    private String errorMessage;
    private Object data;

    public LogicRunTimeException() {
        super();
    }

    public LogicRunTimeException(String errCode) {
        this.errorCode = errCode;
    }

    public LogicRunTimeException(String errorCode, Object data) {
        super();
        this.errorCode = errorCode;
        this.data = data;
    }

    public LogicRunTimeException(String errCode, String errMsg) {
        this.errorCode = errCode;
        this.errorMessage = errMsg;
    }

    /**
     * 获取错误码
     * @return
     */
    public String getErrorCode() {
        return this.errorCode;
    }

    /**
     * 获取错误消息
     */
    @Override
    public String getMessage() {
        if (StrUtil.isNotBlank(this.errorMessage)) {
            return this.errorMessage;
        }
        String errCode = getErrorCode();
        if (StrUtil.isNotBlank(errCode)) {
            return messageUtil.getMessage(errCode);
        }
        return super.getMessage();
    }

    /**
     * 获取错误RestResponse对象
     * @return
     */
    public RestResult<?> getFailedResponse() {
        return RestResult.newFailedInstance(getErrorCode(), getMessage());
    }

    public static void throwLogicException(String errCode, String errMsg) throws LogicRunTimeException {
        throw new LogicRunTimeException(errCode, errMsg);
    }

    public static void throwLogicException(String errCode) throws LogicRunTimeException {
        throwLogicException(errCode, null);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        LogicRunTimeException.messageUtil = applicationContext.getBean(I18nMessagesUtil.class);
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

}
